package xiaoa.java.utils;

import java.security.MessageDigest;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * md5 工具类
 * @author xiaoa
 * @date 2017年12月9日 下午9:04:19
 * @version V1.0
 *
 */
public class Md5Utils {


	public static String byteArrayToString(byte[] b) {

		StringBuffer resultSb = new StringBuffer();

		for (int i = 0; i < b.length; i++) {

			resultSb.append(byteToNumString(b[i]));
		}

		return resultSb.toString();

	}

	private static String byteToNumString(byte b) {

		int _b = b;

		if (_b < 0) {

			_b = 256 + _b;

		}

		return String.valueOf(_b);

	}


	/**
	 * md5 加密16位
	 * @Title: MD5Encode16
	 * @param origin
	 * @return
	 * @author xiaoa
	 */
	public static String encode16(String origin) {

		String resultString = origin;

		try {

			MessageDigest md = MessageDigest.getInstance("MD5");

			resultString = byteArrayToString(md.digest(resultString.getBytes()));
			
			if (resultString.length() > 16){
				resultString = resultString.substring(resultString.length() - 16 , resultString.length());
			}
		}catch (Exception ex) {
			ex.printStackTrace();
		}

		return resultString;

	}
	
	
	/**
	 * md5 加密32位
	 * @Title: MD5Encode16
	 * @param origin
	 * @return
	 * @author xiaoa
	 */
	public static String encode32(String origin) {
		
		if (origin == null || origin.isEmpty()){
			return null;
		}

		return DigestUtils.md5Hex(origin);
	}



}
